import React from 'react';
import PropTypes from 'prop-types'
import { observer, inject } from 'mobx-react';
import TA from '../../../stores/technical_article'
import './index.scss';
import Pagination from '../../../components/pagination/index';
import ListItem from './list_item';
// 请求函数

@inject((stores) => {
  const store = {
    ta: stores.ta,
  }
  return store
})
@observer
class ArcList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
    }
    this.changePage = this.changePage.bind(this)
  }
  componentDidMount() {
    // 请求文章列表和请求文章个数同时完成
    this.getList(this.state.page)
  }
  componentWillUnmount() {
    this.props.ta.cancel()
  }
  // 请求文章列表，返回一个Promise
  getList(page) {
    const { cateId, perPage } = this.props
    Promise.all([this.props.ta.getTa(cateId, perPage, page),
      this.props.ta.getTotal(cateId)])
  }
  // 点击分页列表的回调
  changePage(current) {
    this.setState({
      page: current,
    })
    this.getList(current)
  }
  asyncBootstrap() {
    return new Promise((resolve, reject) => {
      const { cateId, perPage } = this.props
      const { page } = this.state
      Promise.all([this.props.ta.getTa(cateId, perPage, page),
        this.props.ta.getTotal(cateId)])
        .then(() => {
          resolve(true)
        }).catch(reject)
    })
  }
  render() {
    const data = this.props.ta.arcList.get(`list${this.props.cateId}${this.state.page}`);
    const { total } = this.props.ta
    return (
      <div className="article-list">
        {data && data.length ? data.map((item, index) => (
          <ListItem data={item} key={item.id} number={index + 1} />
        )) :
        <div className="loading">加载中...</div>
        }
        <div className="pagination">
          {// 页数大于1显示分页
            total && total > this.props.perPage ? <Pagination total={total} pageSize={this.props.perPage} current={this.state.page} onChange={this.changePage} /> : ''
          }
        </div>
      </div>
    )
  }
}
export default ArcList;
ArcList.propTypes = {
  perPage: PropTypes.number,
  cateId: PropTypes.number,
  // getCurrentTitle: PropTypes.func,
  ta: PropTypes.instanceOf(TA),
}
